﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FbKPI.Facade;
using FbKPI.Model;
using FbKPI.Facade.Validator;
using System.Transactions;

namespace FBKPI.Pages
{
    public partial class InputAchievementPage : System.Web.UI.Page
    {
        protected override void OnPreRender(EventArgs e)
        {
            //ViewState["update"] = Session["update"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 

                int ID = Convert.ToInt32(Request.QueryString["KPI"]);
                hfKpiId.Value = Request.QueryString["KPI"];
                hfKpiAssignId.Value = Request.QueryString["KPIAssign"];
                hfKpiAssignDetailId.Value = Request.QueryString["KPIAssignDetail"];

                IList<string> Status = new List<string>();
                foreach (KPIStatus x in new KPIStatusFacade().GetAllKPIStatus().ToList())
                {
                    //Status.Add(x.Description);
                    ddl_statusbyuser.Items.Add(new ListItem(x.Description, x.ID.ToString()));
                }

                ddl_statusbyuser.Items.Insert(0, new ListItem("---pilih status---", "0"));
                
                if (ID != 0)
                {
                    KPIFacade df = new KPIFacade();
                    KPI KPIs = df.GetKPIByID(ID);

                    if (KPIs != null)
                    {
                        hfKpiId.Value = KPIs.ID.ToString();
                        txt_kpidescription.Text = KPIs.Description;
                        chk_active.Checked = KPIs.isActive;

                        //chk_weightenableflag.Checked = KPIs.WeightEnableFlag;
                        //chk_uomenableflag.Checked = KPIs.UoMEnableFlag;
                        //chk_scoredbysystem.Checked = KPIs.ScoredBySystem;
                        //ScoredBySystem.Value = KPIs.ScoredBySystem.ToString();

                        txt_kpigroup.Text = KPIs.GroupKPI == null ? "" : KPIs.GroupKPI.Description;
                        txt_kpicategory.Text = KPIs.CategoryKPI == null ? "" : KPIs.CategoryKPI.Description;
                        txt_kpitype.Text = KPIs.TypeKPI == null ? "" : KPIs.TypeKPI.Description;                        
                        txt_kpisubtype.Text = KPIs.SubTypeKPI == null ? "" : KPIs.SubTypeKPI.Description;
                        //txt_kpiuom.Text = KPIs.UoM == null ? "" : KPIs.UoM.Description;
                        //txt_kpiuommax.Text = KPIs.UoMDetailMax == null ? "" : KPIs.UoMDetailMax.Description + " || " + KPIs.UoMDetailMax.ListValue;
                        //txt_kpiuommin.Text = KPIs.UoMDetailMin == null ? "" : KPIs.UoMDetailMin.Description + " || " + KPIs.UoMDetailMin.ListValue;

                        //txt_kpiparent.Text = KPIs.KPIParent == null ? "" : KPIs.KPIParent.Description;
                        //txt_kpireplacement.Text = KPIs.KPIReplacement == null ? "" : KPIs.KPIReplacement.Description;

                        txt_kpiyear.Text = KPIs.Year.ToString();
                        txt_weight.Text = KPIs.Weight.ToString();
                        txt_kpiperiode.Text = KPIs.Periode;
                        txt_polarization.Text = KPIs.Polarization;

                        //txt_kpitargetdescription.Text = KPIs.TargetDescription;
                        //txt_kpimanualcalculation.Text = KPIs.ManualCalculation.ToString();
                        //txt_calculationtype.Text = KPIs.KPICalculationType;
                        //txt_replacementdate.Text = KPIs.ReplacementDate == null ? "" : Convert.ToDateTime(KPIs.ReplacementDate).ToShortDateString();
                        //txt_replacementdescription.Text = KPIs.ReplacementDescription;
                        //txt_detailinformation.Text = KPIs.KPIDetailInformation;
                        //txt_strategicobjective.Text = KPIs.KPIStrategicObjective;

                        //txt_uomformat.Value = KPIs.UoM.Format.ToString();

                        //txt_achievementyear.Text = KPIs.Year.ToString();

                        //if (KPIs.UoM.Format == UoMFormat.Month)
                        //{
                        //    txt_realizationmonth.Visible = true;
                        //    txt_realization.Visible = false;
                        //}
                        //else
                        //{
                        //    txt_realizationmonth.Visible = false;
                        //    txt_realization.Visible = true;
                        //}

                        txtMethod.Text = KPIs.Method.MethodName;
                        string statusUser = string.Empty;
                        KPIAchievementFacade acvfacade = new KPIAchievementFacade();
                        string statusVerificator ="";
                        List<KPIAchievement> list = acvfacade.GetListKPIAchievement(Convert.ToInt32(hfKpiAssignId.Value));
                        if (list.Count > 0)
                        {
                            hfTotalDataAchievment.Value = list.Count.ToString();

                            foreach (KPIAchievement data in list)
                            {
                                statusUser = data.StatusByUser.ID.ToString() ;
                                statusVerificator =data.StatusByVerificator.ToString();
                                break;
                            }

                            ddl_statusbyuser.Items.FindByValue(statusUser).Selected = true;
                        }

                        KPIAttachmentFacade attcFacade = new KPIAttachmentFacade();
                        IList<KPIAttachment> listAttc = attcFacade.GetKPIAttachmentByKPIAssign_ByKpiId_KpiAssign_KpiAssignDtl(Convert.ToInt32(hfKpiId.Value), Convert.ToInt32(hfKpiAssignId.Value), Convert.ToInt32(hfKpiAssignDetailId.Value));
                        hfTotalDataAttachment.Value = listAttc.Count.ToString();

                        IList<KPI> listKpiChild = df.GetKPIChilds(KPIs);
                        hfTotalDataKpiChild.Value = listKpiChild.Count.ToString();

                        if (statusVerificator == "1")
                            statusVerificator = "On Progress";
                        else if (statusVerificator == "2")
                            statusVerificator = "UnDone";
                        else if (statusVerificator == "3")
                            statusVerificator = "Done";
                        else
                            statusVerificator = "None";

                        lblVerificator.Text = statusVerificator;

                        if (KPIs.SignEmployeeID != 0)
                        {
                            if (Context.Session["UserLoggedIn"] != null)
                            {
                                int UserID = Convert.ToInt32(Context.Session["UserLoggedIn"]);

                                if (UserID != KPIs.SignEmployeeID)
                                    btn_save.Visible = false;
                                else
                                    btn_save.Visible = true;
                            }
                        }
                          
                    }

                   
                    

                }

                

                //ddl_statusbyuser.DataSource = Status;
                //ddl_statusbyuser.DataBind();

                ////ddl_statusbyverificator.DataSource = Status;
                ////ddl_statusbyverificator.DataBind();

                //ClearContent();

            }

        }

        protected void SaveAction(object sender, EventArgs e)
        {
            //try
            //{
            //    if (Session["update"].ToString() == ViewState["update"].ToString())
            //    {
            //        if (State.Value == "False")
            //        {

            //            HttpFileCollection hfcCek = Request.Files;
            //            int jumlahUpload =0;

            //            for (int i = 0; i < hfcCek.Count; i++)
            //            {
            //                jumlahUpload += hfcCek[i].ContentLength;
            //            }
            //            int maxFileSize = 102400;
            //            if (jumlahUpload > (maxFileSize * 1024))
            //            {
            //                //PanelError.Visible = true;
            //                //lblError.Text = "Filesize of image is too large. Maximum file size permitted is " + maxFileSize + "KB";
            //                Response.Write("<script>alert('" + "Filesize of image is too large. Maximum file size permitted is " + maxFileSize + "KB" + "');</script>");
            //                return;
            //            }

            //            Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(Request.QueryString["User"]));

            //            KPIAchievement Achievement = new KPIAchievement();
            //            Achievement.ID = 0;
            //            Achievement.KPIAssign = new KPIAssignFacade().GetKPIAssignByID(Convert.ToInt32(KPIAssign.Value));
            //            Achievement.Month = Convert.ToInt16(txt_monthnumber.Value);
            //            Achievement.Year = Convert.ToInt16(txt_achievementyear.Text);

            //            if (Achievement.KPIAssign.KPI.UoM.Format == UoMFormat.Month)
            //                Achievement.Realization = txt_realizationmonth.Text;
            //            else
            //                Achievement.Realization = txt_realization.Text;

            //            //Achievement.Realization = txt_realization.Text;
            //            Achievement.Notes = txt_remark.Text;
            //            Achievement.Score = txt_score.Text;
            //            Achievement.StatusByUser = new KPIStatusFacade().GetKPIStatusByID(ddl_statusbyuser.SelectedIndex + 1);
            //            Achievement.isActive = true;
            //            Achievement.CreateBy = CurrUser.Email;
            //            Achievement.isLocked = chk_locked.Checked == true ? true : false;

            //            KPIAchievementFacade af = new KPIAchievementFacade();
            //            KPIAchievementValidator av = new KPIAchievementValidator();

            //            string msg = av.ValidateOnSave(Achievement);
            //            if (msg == "OK")
            //            {
            //                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            //                {
            //                    try
            //                    {
            //                        msg = af.Save(Achievement);

            //                        //attachment upload handler
            //                        if (msg.Contains("Success"))
            //                        {
            //                            HttpFileCollection hfc = Request.Files;
                                        
            //                            for (int i = 0; i < hfc.Count; i++)
            //                            {
            //                                HttpPostedFile hpf = hfc[i];
                                            
            //                                if (hpf.ContentLength > 0)
            //                                {
            //                                    //format filename = kpiassignid_month_year_index_originalname
            //                                    string path = System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"].ToString();
            //                                    string filename = KPIAssign.Value + "_" + Achievement.Month.ToString() + "_" + Achievement.Year.ToString() + "_" + (i + 1).ToString() + "_" + hpf.FileName.Replace(" ", "_").Replace("&", "_Dan_");
            //                                    string a = hpf.FileName.Replace(hpf.FileName, filename);

            //                                    KPIAttachment attachment = new KPIAttachment();
            //                                    attachment.ID = 0;
            //                                    attachment.KPI = new KPIFacade().GetKPIByID(Convert.ToInt32(KPI.Value));
            //                                    attachment.KPIAssign = new KPIAssignFacade().GetKPIAssignByID(Convert.ToInt32(KPIAssign.Value));
            //                                    attachment.KPIAssignDetail = new KPIAssignDetailFacade().GetKPIAssignDetailByID(Convert.ToInt32(KPIAssignDetail.Value));
            //                                    attachment.DocumentFileName = filename;
            //                                    attachment.isActive = true;
            //                                    attachment.CreateBy = CurrUser.Email;

            //                                    hpf.SaveAs(Server.MapPath("~/Attachment/")+ hpf.FileName.Replace(hpf.FileName, filename));

            //                                    KPIAttachmentFacade atf = new KPIAttachmentFacade();
            //                                    msg = atf.Save(attachment);

            //                                    if (!msg.Contains("Success"))
            //                                    {
            //                                        int x = 0;
            //                                        int y = 1;
            //                                        int z = y / x;
            //                                    }
            //                                }
            //                            }
            //                        }
            //                        Response.Write("<script>alert('" + msg + "');</script>");
            //                        ClearContent();
            //                    }
            //                    catch (Exception ex)
            //                    {

            //                        Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //                        logwriter.WriteLog(ex.Message, ex.StackTrace.ToString());
            //                        Response.Write("<script>alert('" + msg + "');</script>");
            //                    }
            //                    finally
            //                    {
            //                        trans.Complete();
            //                        trans.Dispose();
            //                    }
            //                }
            //            }
            //            else
            //            {
            //                Response.Write("<script>alert('" + msg + "');</script>");
            //            }
            //            Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
            //        }
            //        else if (State.Value == "Wait")
            //        {
            //            KPIAchievement Achievement = new KPIAchievementFacade().GetKPIAchievementDetail(Convert.ToInt32(txt_monthnumber.Value), Convert.ToInt32(txt_achievementyear.Text), Convert.ToInt32(KPIAssign.Value));
            //            Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(Request.QueryString["User"]));

            //            if (Achievement != null)
            //            {
            //                Achievement.Notes = txt_remark.Text;
            //                Achievement.Score = txt_score.Text;

            //                if (Achievement.KPIAssign.KPI.UoM.Format == UoMFormat.Month)
            //                    Achievement.Realization = txt_realizationmonthtext.Value;
            //                else
            //                    Achievement.Realization = txt_realization.Text;

            //                Achievement.StatusByVerificator = null;
            //                Achievement.CreateBy = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(Request.QueryString["User"])).Email;
            //                Achievement.isLocked = chk_locked.Checked;

            //                KPIAchievementFacade af = new KPIAchievementFacade();
            //                KPIAchievementValidator av = new KPIAchievementValidator();

            //                string msg = av.ValidateOnSave(Achievement);
            //                if (msg == "OK")
            //                {
            //                    using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            //                    {
            //                        try
            //                        {
            //                            msg = af.Save(Achievement);

            //                            if (!msg.Contains("Success"))
            //                            {
            //                                int x = 0;
            //                                int y = 1;
            //                                int z = y / x;
            //                            }
            //                            else
            //                            {
            //                                IList<KPIAttachment> Attachments = new KPIAttachmentFacade().GetKPIAttachmentByKPIAssign(Convert.ToInt32(KPIAssign.Value), Convert.ToInt32(Achievement.Month), Convert.ToInt32(Achievement.Year));
            //                                if (Attachments != null && Attachments.Count > 0)
            //                                {
            //                                    foreach(KPIAttachment a in Attachments)
            //                                    {
            //                                        msg = new KPIAttachmentFacade().Delete(a);
            //                                    }
            //                                }

            //                                HttpFileCollection hfc = Request.Files;
            //                                for (int i = 0; i < hfc.Count; i++)
            //                                {
            //                                    HttpPostedFile hpf = hfc[i];
            //                                    if (hpf.ContentLength > 0)
            //                                    {
            //                                        //format filename = kpiassignid_month_year_index_originalname
            //                                        string path = System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"].ToString();
            //                                        string filename = KPIAssign.Value + "_" + Achievement.Month.ToString() + "_" + Achievement.Year.ToString() + "_" + (i + 1).ToString() + "_" + hpf.FileName.Replace(" ", "_").Replace("&", "_Dan_");
            //                                        string a = hpf.FileName.Replace(hpf.FileName, filename);

            //                                        KPIAttachment attachment = new KPIAttachment();
            //                                        attachment.ID = 0;
            //                                        attachment.KPI = new KPIFacade().GetKPIByID(Convert.ToInt32(KPI.Value));
            //                                        attachment.KPIAssign = new KPIAssignFacade().GetKPIAssignByID(Convert.ToInt32(KPIAssign.Value));
            //                                        attachment.KPIAssignDetail = new KPIAssignDetailFacade().GetKPIAssignDetailByID(Convert.ToInt32(KPIAssignDetail.Value));
            //                                        attachment.DocumentFileName = filename;
            //                                        attachment.isActive = true;
            //                                        attachment.CreateBy = CurrUser.Email;

            //                                        hpf.SaveAs(path + hpf.FileName.Replace(hpf.FileName, filename));

            //                                        KPIAttachmentFacade atf = new KPIAttachmentFacade();
            //                                        msg = atf.Save(attachment);

            //                                        if (!msg.Contains("Success"))
            //                                        {
            //                                            int x = 0;
            //                                            int y = 1;
            //                                            int z = y / x;
            //                                        }
            //                                    }
            //                                }
            //                                Response.Write("<script>alert('" + msg + "');</script>");
            //                                ClearContent();
            //                            }
            //                        }
            //                        catch (Exception ex)
            //                        {
            //                            Response.Write("<script>alert('" + msg + "');</script>");
            //                        }
            //                        finally
            //                        {
            //                            trans.Complete();
            //                            trans.Dispose();
            //                        }
            //                    }

            //                }
            //                else
            //                {
            //                    Response.Write("<script>alert('" + msg + "');</script>");
            //                }
            //            }
            //            Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //    logwriter.WriteLog(ex.Message.ToString(), ex.StackTrace.ToString());
            //    Response.Redirect("../login.aspx");
            //}
        }

        protected void LockAction(object sender, EventArgs e)
        {
            //if (Session["update"].ToString() == ViewState["update"].ToString())
            //{
            //    if (State.Value == "False")
            //    {
            //        int month = Convert.ToInt32(txt_monthnumber.Value);
            //        int year = Convert.ToInt32(txt_achievementyear.Text);
            //        int KPIAssignID = Convert.ToInt32(KPIAssign.Value);
            //        Employee CurrentUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(Request.QueryString["User"]));

            //        KPIAchievementFacade kf = new KPIAchievementFacade();
            //        string msg = string.Empty;

            //        using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            //        {
            //            try
            //            {
            //                msg = kf.LockKPIAchievement(month, year, KPIAssignID, CurrentUser);

            //                if (!msg.Contains("Success"))
            //                {
            //                    int x = 0;
            //                    int y = 1;
            //                    int z = y / x;
            //                }
            //                else
            //                {
            //                    Response.Write("<script>alert('" + msg + "');</script>");
            //                    ClearContent();
            //                }
            //            }
            //            catch (Exception ex)
            //            {
            //                Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //                logwriter.WriteLog(ex.Message, ex.StackTrace.ToString());
            //                Response.Write("<script>alert('" + msg + "');</script>");
            //            }
            //            finally
            //            {
            //                trans.Complete();
            //                trans.Dispose();
            //            }
            //        }

            //        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
            //    }
            //}
        }

        private void ClearContent()
        {
            //State.Value = string.Empty;
            //txt_month.Text = string.Empty;
            //txt_monthnumber.Value = string.Empty;
            //txt_realization.Text = string.Empty;
            //txt_realizationmonth.Text = string.Empty;
            //ddl_statusbyuser.SelectedIndex = 0;
            //ddl_statusbyverificator.SelectedIndex = 0;
            //txt_score.Text = string.Empty;
            //txt_remark.Text = string.Empty;
        }
    }
}